<?php

class Bookings extends Controller {



	function Bookings()
	{
		parent::Controller();
		$this->load->helper(array('url', 'date', 'dropdownlist'));	
		$this->load->library('session');
	}
	
	function index()
	{
		$this->load->view('bookings/index');
	}
	
	function search_availability_widget()
	{
		$this->load->model('Tour_model', '', TRUE);
		
		$data = array();
		$data['results'] = $this->Tour_model->get_tours_for_booking($_POST);
		$data['passengers'] = $_POST['booking_passengers'];
		$data['admin'] = $_POST['admin'];
		
		$this->load->view('bookings/tour_availability', $data);
	}	
	
	function step1() //pick a tour
	{
	
	$this->load->helper('bookings');
		$this->load->model('Booking_model', '', TRUE);
		
		$this->load->model('Tourtype_model', '', TRUE);
		
		
		$this->load->library('form_validation');
		$this->form_validation->set_rules('booking_tour', 'Tour', 'required');			
		$this->form_validation->set_rules('booking_passengers', 'Number of passengers', 'required|numeric');	
		$data = array();
		
		$data['tourtypes'] = $this->Tourtype_model->get_all_tourtypes();
		
		if(!isset($_POST['go_to_step2'])) //when the user arrived on the page
		
			$this->load->view('bookings/step1',$data);		
		
		else if (isset($_POST['go_to_step2']) && $this->form_validation->run() == TRUE) //if all right
		{
		  $newdata = array(
                   'booking_tour'  => $_POST['booking_tour'],
                   'booking_passengers'     => $_POST['booking_passengers']
               );
		  
		  $this->session->set_userdata($newdata);
		  redirect(site_url("bookings/step2"));
		} else
		{
			$this->load->view('bookings/step1',$data); //if the form is not complete
		}
	}
	
	
	function step2() //user details
	{
		
	    //check if the datas of the previous step are loaded in the session
		$test = $this->session->userdata('booking_tour');
		if(!empty($test))
		{		
			//booking_user_id is set if the user is already in the database, we unset the variable
			//in case the user go back to step 2 and decide to not use the existing user
			if($this->session->userdata('booking_user_id'))
				$this->session->unset_userdata('booking_user_id');
			
			$this->load->library('form_validation');
			$this->form_validation->set_rules('booking_first_name', 'First Name', 'trim|required');
			$this->form_validation->set_rules('booking_last_name', 'Last Name', 'trim|required');
			$this->form_validation->set_rules('booking_sex', 'Sex', 'trim|required');
			$this->form_validation->set_rules('booking_nationality', 'Nationality', 'trim|required');
			$this->form_validation->set_rules('booking_country', 'Country', 'trim|required');
			$this->form_validation->set_rules('booking_email', 'E-mail address', 'trim|required|valid_email');
			$this->form_validation->set_rules('booking_phone', 'Telephone number', 'trim|required|check_phone');
			$this->form_validation->set_rules('booking_city', 'City', 'trim');
			$this->form_validation->set_rules('booking_post_code', 'Post Code', 'trim');
			$this->form_validation->set_rules('booking_address', 'Address', 'trim');			


			$data['links_list'] = 	array(
										array('link' => 'step1', 'value' => "Step 1"),
									);			
			
			if(!isset($_POST['go_to_step3'])) //when the user arrived on the page
				$this->load->view('bookings/step2',$data);		
			else if (isset($_POST['go_to_step3']) && $this->form_validation->run() == TRUE) //if all right
			{
				$password =substr( md5( time() . rand() . $_POST['booking_email'] ), 0, 12 );
				$marketing = (isset($_POST['booking_marketing']) && $_POST['booking_marketing'] == 1) ? 1 : 0;
				$newdata = array(
					   'booking_first_name'  => $_POST['booking_first_name'],
					   'booking_last_name'     => $_POST['booking_last_name'],
					   'booking_sex'     => $_POST['booking_sex'],
					   'booking_nationality'  => $_POST['booking_nationality'],
					   'booking_email'  => $_POST['booking_email'],
					   'booking_phone'     => $_POST['booking_phone'],
					   'booking_country'     => $_POST['booking_country'],
					   'booking_city'     => $_POST['booking_city'],
					   'booking_post_code'  => $_POST['booking_post_code'],
					   'booking_address'     => $_POST['booking_address'],					   
					   'booking_marketing'     => $marketing,	
					   'booking_password'	=> $password				   
					   );
			  
				//check if the user already exists
				$this->load->model('User_model', '', TRUE);
				if($this->User_model->user_exists($_POST['booking_email']))
				{
					$serialized_data = serialize($newdata);
					redirect(site_url("bookings/check_user/".$serialized_data));
				}
				else
				{
					$this->session->set_userdata($newdata);
					redirect(site_url("bookings/step3"));
			  }
			}		
			else
			{			
				$this->load->view('bookings/step2',$data);		//if the form is not complete
			}
		}
		else //no var in the session -> back to the step one (pick a tour)
			redirect(site_url("bookings/step1"));
	}
	
	function step3()  //passengers details
	{
	    
		//check if the datas of the previous step are loaded in the session
		$first_name = $this->session->userdata('booking_first_name');
		if(!empty($first_name))
		{	
			$this->load->library('form_validation');	
			for($i = 0; $i < $this->session->userdata('booking_passengers'); $i++)
			{
				$this->form_validation->set_rules('booking_passenger_first_name['.$i.']', 'First Name', 'trim|required');
				$this->form_validation->set_rules('booking_passenger_last_name['.$i.']', 'Last Name', 'trim|required');
				$this->form_validation->set_rules('booking_passenger_sex['.$i.']', 'Sex', 'trim|required');
				$this->form_validation->set_rules('booking_passenger_nationality['.$i.']', 'Nationality', 'trim|required');
				if($i == 0) $this->form_validation->set_rules('booking_passenger_emergency['.$i.']', 'Emergency phone number', 'trim|required|check_phone');				
				else $this->form_validation->set_rules('booking_passenger_emergency['.$i.']', 'Emergency phone number', 'trim|check_phone');								
					
			}

			$data = array(
				'booking_first_name'  => $first_name,
				'booking_last_name'  => $this->session->userdata('booking_last_name'),
			    'booking_sex'     => $this->session->userdata('booking_sex'),
				'booking_number_passengers'     => $this->session->userdata('booking_passengers'),
				'booking_nationality'  => $this->session->userdata('booking_nationality'),
				'booking_email'  => $this->session->userdata('booking_email'),
				'booking_phone'     => $this->session->userdata('booking_phone'),
				'booking_country'     => $this->session->userdata('booking_country'),
				'booking_city'     => $this->session->userdata('booking_city'),
				'booking_post_code'  => $this->session->userdata('booking_post_code'),
				'booking_address'     => $this->session->userdata('booking_address')					
				);
				

			$data['links_list'] = 	array(
							array('link' => 'step1', 'value' => "Step 1"),
							array('link' => 'step2', 'value' => "Step 2"),							
						);

			if(!isset($_POST['go_to_step4'])) //when the user arrived on the page
				$this->load->view('bookings/step3',$data);
			else if (isset($_POST['go_to_step4']) && $this->form_validation->run() == TRUE) //if all right
			{
   			   $all_passengers = array();
			   	for($i = 0; $i < $this->session->userdata('booking_passengers'); $i++)
				{
				   $all_passengers[$i] = array(
					   'first_name'  => $_POST['booking_passenger_first_name'][$i],
					   'last_name'     => $_POST['booking_passenger_last_name'][$i],
					   'sex'     => $_POST['booking_passenger_sex'][$i],
					   'nationality'     => $_POST['booking_passenger_nationality'][$i],					   
					   'emergency_phone_number'     => $_POST['booking_passenger_emergency'][$i]
				   );
			   }
			  
			  $this->session->set_userdata('passengers',$all_passengers);
			  redirect(site_url("bookings/step4"));
			}
			else
				$this->load->view('bookings/step3',$data);
		}
		else //no var in the session -> back to the step two (user details)
			redirect(site_url("bookings/step2"));		
	
	}
	
	function step4() //confirmation
	{
	    //check if the datas of the previous step are loaded in the session
		$passengers = $this->session->userdata('passengers');
		if(!empty($passengers))
		{	
			$tour_id = $this->session->userdata('booking_tour');
			
			$this->load->library('form_validation');	
			$this->form_validation->set_rules('booking_terms', 'Accept', 'required');
			$this->form_validation->set_rules('booking_promo_code', 'Promotion code', 'trim');			
			$this->form_validation->set_message('required', 'You have to accept the Terms an Conditions to continue');
			
			$this->load->model('Tour_model', '', TRUE);
		    $tourinfo = $this->Tour_model->get_tour_info($tour_id);

    	    $data = array (
					'booking_tour' => $tourinfo,
					'booking_first_name'  => $this->session->userdata('booking_first_name'),
					'booking_last_name'  => $this->session->userdata('booking_last_name'),
					'booking_sex'     => $this->session->userdata('booking_sex'),					
					'booking_nationality'  => $this->session->userdata('booking_nationality'),
					'booking_email'  => $this->session->userdata('booking_email'),
					'booking_phone'     => $this->session->userdata('booking_phone'),
					'booking_country'     => $this->session->userdata('booking_country'),
					'booking_city'     => $this->session->userdata('booking_city'),
					'booking_post_code'  => $this->session->userdata('booking_post_code'),
					'booking_address'     => $this->session->userdata('booking_address'),
					'booking_passengers'     => $this->session->userdata('passengers')					
			 );
			$data['links_list'] = 	array(
									array('link' => 'step1', 'value' => "Step 1"),
									array('link' => 'step2', 'value' => "Step 2"),							
									array('link' => 'step3', 'value' => "Step 3"),							
								);	

			if(isset($_POST['booking_promo_code']) && (!empty($_POST['booking_promo_code'])) ) 
			{
				$price_off = 3.70;
				$data['price_off'] = $price_off;
			}					
			
			if(isset($_POST['confirm']) &&  $this->form_validation->run() == TRUE) 
			{
				$this->session->set_userdata('booking_total',$_POST['booking_total']);
				redirect(site_url("bookings/step5"));	
			}
			else
				$this->load->view('bookings/step4',$data);
		}
		else
			redirect(site_url("bookings/step3"));		
	}

	function step5() 
	{
		$total = $this->session->userdata('booking_total');
		if(!empty($total))
		{
			$this->load->library('form_validation');	
			$this->form_validation->set_rules('booking_amount_paid', 'Amount paid', 'trim|required|numeric');			
			$this->form_validation->set_rules('booking_payment_method', 'Payment method', 'trim|required');	
			$this->form_validation->set_rules('booking_payment_location', 'Payment location', 'trim|required');				
			$data['booking_total']	= $total;
			
			if(isset($_POST['proceed']) &&  $this->form_validation->run() == TRUE) 
			{
				$this->session->set_userdata('booking_amount_paid',$_POST['booking_amount_paid']);
				$this->session->set_userdata('booking_payment_method',$_POST['booking_payment_method']);
				$this->session->set_userdata('booking_payment_location',$_POST['booking_payment_location']);

				if(!$this->session->userdata('booking_inserted')) // in order to not insert the booking twice
				{
					//user insertion
					$this->load->model('User_model', '', TRUE);
					
					$data_user = array (
						'first_name'  => $this->session->userdata('booking_first_name'),
						'last_name'  => $this->session->userdata('booking_last_name'),
						'sex'     => $this->session->userdata('booking_sex'),					
						'nationality'  => $this->session->userdata('booking_nationality'),
						'e_mail'  => $this->session->userdata('booking_email'),
						'phone_number'     => $this->session->userdata('booking_phone'),
						'country'     => $this->session->userdata('booking_country'),
						'city'     => $this->session->userdata('booking_city'),
						'post_code'  => $this->session->userdata('booking_post_code'),
						'address'     => $this->session->userdata('booking_address'),
						'marketing' => $this->session->userdata('booking_marketing'),
						'password' => $this->session->userdata('booking_password')
						
					);
					if($this->session->userdata('booking_user_id'))
					{	
						$user_id = $this->session->userdata('booking_user_id');
						$this->User_model->update_user($user_id,$data_user);
						
					}
					else
						$user_id = $this->User_model->insert_user($data_user);
					
					//booking insertion
					$this->load->model('Booking_model', '', TRUE);
					$this->load->model('Tour_model', '', TRUE);
					$date = date("Y-m-d H:m:s");
					$data_booking = array (
						'tour_id' => $this->session->userdata('booking_tour'),
						'user_id' => $user_id,
						'booking_date' => $date
					);		
					$id_booking = $this->Booking_model->insert_booking($data_booking,$this->session->userdata('booking_passengers'));
					//generate the booking_number Macbs_TourCode_DepartureDate_nbPassengers_bookingID
					$tour_id = $this->session->userdata('booking_tour');
					$passengers_number = $this->session->userdata('booking_passengers');
					$tour_code = $this->Tour_model->get_tourcode($tour_id);
					$departure_date = $this->Tour_model->get_departure($tour_id);
					$booking_number = "Macbc_".$tour_code."_".$departure_date."_".$passengers_number."_".$id_booking;
					$new_data = array('booking_number' => $booking_number);
					$this->Booking_model->update_booking($id_booking, $new_data);
										
					//passengers insertion
					$this->load->model('Passenger_model', '', TRUE);
					$passengers = $this->session->userdata('passengers');
					foreach($passengers as $passenger)
					{
					   $passenger['booking_id'] = $id_booking;
					   $this->Passenger_model->insert_passenger($passenger);
					}				
					
					//payment insertion
					$this->load->model('Payment_model', '', TRUE);
					$payment_auth = md5( time() . rand() . $data_user['e_mail'] );
					$data_payment = array(
									'booking_id' => $id_booking,
									'amount' => $this->session->userdata('booking_amount_paid'),
									'method' => $this->session->userdata('booking_payment_method'),
									'location' => $this->session->userdata('booking_payment_location'),
									'payment_auth' => $payment_auth,
									'payment_receive'	 => 1,
									'payment_date' => date("Y-m-d H:m:s")
					);
					$this->Payment_model->insert_payment($data_payment);
					
					$this->session->set_userdata('booking_inserted',TRUE);

					redirect(site_url("bookings/step6/$id_booking"));	
				}
			}
			
			$data['links_list'] = 	array(
					array('link' => 'step1', 'value' => "Step 1"),
					array('link' => 'step2', 'value' => "Step 2"),							
					array('link' => 'step3', 'value' => "Step 3"),							
					array('link' => 'step4', 'value' => "Step 4"),																
				);		
			
			$this->load->view('bookings/step5',$data);
		}
		else
			redirect(site_url("bookings/step4"));		
	}
	
	function step6($booking_id)
	{
		$insert = $this->session->userdata('booking_inserted');
		if($insert)
		{
			$this->load->model('User_model', '', TRUE);
			$this->load->model('Tour_model', '', TRUE);
			$this->load->model('Passenger_model', '', TRUE);
			$this->load->model('Payment_model', '', TRUE);		
			$this->load->model('Booking_model', '', TRUE);
						
			$user = $this->User_model->get_user_booking($booking_id);
			$tour = $this->Tour_model->get_tour_booking($booking_id);
			$passengers = $this->Passenger_model->get_passengers_booking($booking_id);
			$payments = $this->Payment_model->get_payment_booking($booking_id);
			$booking = $this->Booking_model->get_booking($booking_id);

			$data = array(
					'user' => $user,
					'tour' => $tour,
					'passengers' => $passengers,
					'payments' => $payments,
					'booking' => $booking
			);
			//TODO
			//send an e-mail to the user (password..)
			// $this->load->library('email');
			
			// $this->email->from("webmaster@macBackpackers.com", 'MacBackpackers');
			// $this->email->to($user['e_mail']);
			// $this->email->subject('Tour booking');
			// $this->email->message('Testing the email class.');
			// $this->email->send();
			// echo $this->email->print_debugger();
			
			
			$this->load->view('bookings/step6',$data);
		}
		else
			redirect(site_url("bookings/step5"));	
	
	}
	

	function check_user($serialized_data) 
	{
		//datas entered in the form
		$user_form = unserialize($serialized_data);
		//datas from the DB
		$this->load->model('User_model', '', TRUE);
		$user_db = $this->User_model->get_user_by_mail($user_form['booking_email']);
		
		//get the different fields
		$tab_diff = $this->compare_users($user_form,$user_db);
		
		if(isset($_POST['go_to_step2'])) 
			redirect(site_url("bookings/step2"));	
		elseif(isset($_POST['go_to_step3'])) 
		{
			
			$newdata = array(
				'booking_user_id' => $user_db['user_id'],
				'booking_first_name'  => $user_db['first_name'],
				'booking_last_name'     => $user_db['last_name'],
				'booking_sex'     => $user_db['sex'],
				'booking_nationality'  => $user_db['nationality'],
				'booking_email'  => $user_db['e_mail'],
				'booking_phone'     => $user_db['phone_number'],
				'booking_country'     => $user_db['country'],
				'booking_city'     => $user_db['city'],
				'booking_post_code'  => $user_db['post_code'],
				'booking_address'     => $user_db['address'],					   
				'booking_marketing'     => $user_db['marketing']	
		    );

			//get the modified fields
			if(isset($_POST["choice"]))
			{
				$modified_fields = $_POST["choice"];
				foreach($modified_fields as  $field)
				{
					$tab = explode(" | ",$field);
					$key = $tab[0];
					$value = $tab[1];
					if($key == "First Name")
						$newdata['booking_first_name'] = $value;
					elseif($key == "Last Name")
						$newdata['booking_last_name'] = $value;						
					elseif($key == "Sex")
						$newdata['booking_sex'] = $value;						
					elseif($key == "Nationality")
						$newdata['booking_nationality'] = $value;						
					elseif($key == "E-mail address")
						$newdata['booking_email'] = $value;						
					elseif($key == "Telephone number")
						$newdata['booking_phone'] = $value;						
					elseif($key == "Country")
						$newdata['booking_country'] = $value;						
					elseif($key == "City")
						$newdata['booking_city'] = $value;						
					elseif($key == "Post Code")
						$newdata['booking_post_code'] = $value;						
					elseif($key == "Address")
						$newdata['booking_address'] = $value;						
					elseif($key == "Marketing")
						$newdata['booking_marketing'] = $value;						
				}
			}
			$this->session->set_userdata($newdata);
			redirect(site_url("bookings/step3"));	
		}
		

		$data = array(
				'fields' => $tab_diff,
				'data_serialized' => $serialized_data
				);	

		$this->load->view('bookings/check_user',$data);
		
	}
	
		
	function compare_users($user_form,$user_db) //return an array : 'label' => 'data_form | data_db' if the fields are different
	{
		$tab_fields = array();
		if(trim($user_form['booking_first_name']) != trim($user_db['first_name']))
			$tab_fields['First Name'] = $user_form['booking_first_name'].' | '.$user_db['first_name'];
		if(trim($user_form['booking_last_name']) != trim($user_db['last_name']))
			$tab_fields['Last Name'] = $user_form['booking_last_name'].' | '.$user_db['last_name'];
		if(trim($user_form['booking_sex']) != trim($user_db['sex']))
			$tab_fields['Sex'] = $user_form['booking_sex'].' | '.$user_db['sex'];
		if(trim($user_form['booking_nationality']) != trim($user_db['nationality']))
			$tab_fields['Nationality'] = $user_form['booking_nationality'].' | '.$user_db['nationality'];
		if(trim($user_form['booking_email']) != trim($user_db['e_mail']))
			$tab_fields['E-mail address'] = $user_form['booking_email'].' | '.$user_db['e_mail'];
		if(trim($user_form['booking_phone']) != trim($user_db['phone_number']))
			$tab_fields['Telephone number'] = $user_form['booking_phone'].' | '.$user_db['phone_number'];		
		if(trim($user_form['booking_country']) != trim($user_db['country']))
			$tab_fields['Country'] = $user_form['booking_country'].' | '.$user_db['country'];		
		if(trim($user_form['booking_city']) != trim($user_db['city']))
			$tab_fields['City'] = $user_form['booking_city'].' | '.$user_db['city'];
		if(trim($user_form['booking_post_code']) != trim($user_db['post_code']))
			$tab_fields['Post Code'] = $user_form['booking_post_code'].' | '.$user_db['post_code'];
		if(trim($user_form['booking_address']) != trim($user_db['address']))
			$tab_fields['Address'] = $user_form['booking_address'].' | '.$user_db['address'];
		if(trim($user_form['booking_marketing']) != trim($user_db['marketing']))
			$tab_fields['Marketing'] = $user_form['booking_marketing'].' | '.$user_db['marketing'];
			
		return $tab_fields;
	}
}
?>
